package com.twang.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.email.SendmailService;
import com.twang.stock.entity.DfcfBanKuaiMaoLiLv;
import com.twang.stock.entity.ReDianHotRank;
import com.twang.stock.entity.ThsHotStock;
import com.twang.stock.entity.ThsReDianStock;
import com.twang.stock.mapper.ReDianHotRankMapper;
import com.twang.stock.mapper.ThsReDianStockMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.task.QueryBanKuaiAndDaPan;
import com.twang.stock.task.old.BaseTask;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 同花顺1小时热度榜（）
 */
@Slf4j
@Component
public class TodayReDuOnehourService{

    @Resource
    private ThsReDianStockMapper thsReDianStockMapper;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    @Autowired
    private ThsReDianStockService thsReDianStockService;

    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private ReDianHotRankMapper reDianHotRankMapper;

    @Resource
    private CommonService commonService;
    @Autowired
    private SendmailService sendmailService;

    public void excute() throws Exception {
       热点预警();
       thsReDianStockService.select24HourData(Boolean.FALSE);
   }

    public void 热点预警() throws Exception {
        //1小时
        log.info(">>>>>>>>>>>>>> 热点预警 1小时 start");
        List<ThsHotStock> listOneHourTag= QueryBanKuaiAndDaPan.getHotStockList(QueryBanKuaiAndDaPan.oneHourTag,0);
        insert(listOneHourTag,QueryBanKuaiAndDaPan.oneHourTag);

        //24小时
        log.info(">>>>>>>>>>>>>> 热点预警 24小时 start");
        List<ThsHotStock> listDayTag= QueryBanKuaiAndDaPan.getHotStockList(QueryBanKuaiAndDaPan.dayTag,0);
        insert(listDayTag,QueryBanKuaiAndDaPan.dayTag);

        asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
            try {
                log.info(">>>>>>>>>>>>>> 热点预警 getReDianHotRank start");
                List<DfcfBanKuaiMaoLiLv> list= thsReDianStockService.getReDianHotRank(Boolean.FALSE);
                list.forEach(item->{
                    log.info(">>>>>>>>>>>>>> 热点预警 getReDianHotRank code={}",item.getCode());
                    ReDianHotRank reDianHotRank=item.getReDianHotRank();
                    //更新分钟量能
                    ReDianHotRank temp=new ReDianHotRank();
                    temp.setCode(reDianHotRank.getCode());
                    temp.setDate(HolidayCopy.getRealToday());
                    temp.setIncreaseType(reDianHotRank.getIncreaseType());
                    List<ReDianHotRank> lists = reDianHotRankMapper.query(temp);
                    if(CollectionUtils.isEmpty(lists)){
                        reDianHotRank.setDate(temp.getDate());
                        reDianHotRank.setType(QueryBanKuaiAndDaPan.dayTag);
                        reDianHotRank.setCreateTime(new Date());
                        reDianHotRank.setIncreaseType(temp.getIncreaseType());
                        reDianHotRankMapper.insert(reDianHotRank);
                        asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                            try {
                                String ztDesc = "未查询到信息！";
                                if (CollectionUtils.isNotEmpty(item.getKanDian())) {
                                    ztDesc = item.getKanDian().get(0).getZtDesc();
                                    if (StringUtils.isEmpty(ztDesc)) {
                                        ztDesc = "未查询到信息！";
                                    }
                                }

                                //预警002241
                                //String str="飙升："+item.getName()+"  增加"+reDianHotRank.getRankIncrease()+"关注度！  涨停原因："+ztDesc;
                                StringBuffer content = new StringBuffer();
                                content.append("<div><div style='margin-left:4%;'>");
                                content.append("<p style='color:red;'>");
                                if (reDianHotRank.getIncreaseType().intValue() == 1) {
                                    content.append("【飙升】").append(item.getName()).append(" 增加");
                                } else {
                                    content.append("【骤减】").append(item.getName()).append(" 下降");
                                }
                                content.append(reDianHotRank.getRankIncrease()).append("关注度！：</p>");
                                content.append("<p style='text-indent: 2em;'>涨停原因：").append(ztDesc).append("</p>");
                                content.append("<p style='text-indent: 2em;display: block;word-break: break-all;'>");
                                String url = "http://www.stock520.cn/ths/stockKanDian?type=24Hour&code=redian_" + item.getCode().replace("sz", "").replace("sh", "");
                                content.append("详情查看：<a style='text-decoration: none;' href='" + url + "'>" + url + "</a></p>");
                                String urlInfo = "http://www.stock520.cn/stockKanDian?code=" + item.getCode().replace("sz", "").replace("sh", "");
                                content.append("个股详情：<a style='text-decoration: none;' href='" + urlInfo + "'>" + urlInfo + "</a></p>");
                                content.append("</div>");
                                content.append("<ul style='color: rgb(169, 169, 189);font-size: 18px;'>");
                                content.append("<li>为了保障您帐号的安全，该链接有效期为12小时。</li>");
                                content.append("<li>该链接只能使用一次，请周知。</li>");
                                content.append("<li>如果该链接无法点击，请直接复制以上网址到浏览器地址栏中访问。</li>");
                                content.append("<li>请您妥善保管，此邮件无需回复。</li>");
                                content.append("</ul>");
                                content.append("</div>");
                                List<String> ids= Arrays.asList(commonService.getValue("warn_re_du").toString().split(","));
                                for(String id:ids) {
                                    sendmailService.sendMailWithEmailNew(content.toString(), item.getName(), item.getName(), Long.valueOf(id));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void insert( List<ThsHotStock> list,String type) {
        if (CollectionUtils.isNotEmpty(list)) {
            List<ThsReDianStock> insert = Lists.newArrayList();
            List<ThsReDianStock> update = Lists.newArrayList();
            for (int i = 0; i < list.size(); i++) {
                ThsHotStock item = list.get(i);
                ThsReDianStock thsReDianStock = new ThsReDianStock();
                BeanUtils.copyProperties(item, thsReDianStock);
                thsReDianStock.setStockOrder(new BigDecimal(i + 1));
                if (null != item.getTag()) {
                    thsReDianStock.setTag(JSONObject.toJSONString(item.getTag()));
                }
                if (CollectionUtils.isNotEmpty(item.getSustainTags())) {
                    thsReDianStock.setSustainTags(JSONObject.toJSONString(item.getSustainTags()));
                }
                thsReDianStock.setZhangDie(item.getZhangdie());
                thsReDianStock.setDate(HolidayCopy.getRealToday());
                thsReDianStock.setHour(HolidayCopy.getHHmmss().substring(8, 12));
                thsReDianStock.setCreateTime(new Date());
                thsReDianStock.setType(type);
                //
                Example example = new Example(ThsReDianStock.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("date", thsReDianStock.getDate());
                criteria.andEqualTo("hour", thsReDianStock.getHour());
                criteria.andEqualTo("code", thsReDianStock.getCode());
                criteria.andEqualTo("type", thsReDianStock.getType());
                example.orderBy("id").desc();
                List<ThsReDianStock> listCount = thsReDianStockMapper.selectByExample(example);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(listCount)) {
                    ThsReDianStock last = listCount.get(0);
                    thsReDianStock.setId(last.getId());
                    //thsReDianStockMapper.updateByPrimaryKey(thsReDianStock);
                    update.add(thsReDianStock);

                } else {
                    // thsReDianStockMapper.insert(thsReDianStock);
                    insert.add(thsReDianStock);
                }
            }
            if (CollectionUtils.isNotEmpty(insert)) {
                log.info(">>>>>>>>>>>> batchInsertStocks insert  type={} size={}", type, insert.size());
                thsReDianStockMapper.batchInsertStocks(insert);
            }
            if (CollectionUtils.isNotEmpty(update)) {
                log.info(">>>>>>>>>>>> batchInsertStocks update  type={} size={}", type, update.size());
                thsReDianStockMapper.batchUpdateStocks(update);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        List<ThsHotStock> list=   QueryBanKuaiAndDaPan.getHotStockList(QueryBanKuaiAndDaPan.oneHourTag,1);
        System.out.println("args = " + JSONObject.toJSONString(list));
    }


}
